﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;

using HalconDotNet;
using HWindowExtension;

namespace MyClientDemo
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private TcpClient myTcpClient;//定义TCP客户端
        private NetworkStream mynetworkstream;//网络数据流
        private Thread myReceiveMsgThread;//创建接收消息线程

        ////定义回调（委托），用以完成显示接收到的数据
        //private delegate void ShowReceiveMsgCallBack(string text);
        //ShowReceiveMsgCallBack showReceiveMsgCallBack;//声明回调
        //定义回调（委托），用以完成显示进度条
        //private delegate void ShowProgressBarCallBack();
        //ShowProgressBarCallBack showProgressBarCallBack;//声明回调
        ////定义委托（回调），用以完成状态lab的显示
        //private delegate void ShowLabStateCallBack(string str);
        //ShowLabStateCallBack showLabStateCallBack;//声明回调

        HalconDotNet.HWindowControl hWindowControlWPF1 = null;
        HImage ho_ModelImage;
        HWindowControlEx hWindowControlEx;
        public MainWindow()
        {
            InitializeComponent();

            this.Closing += new System.ComponentModel.CancelEventHandler(MainWindow_Closing);

            this.btnCloseConnection.IsEnabled = false;
            this.btnSendData.IsEnabled = false;




            hWindowControlEx = new HWindowControlEx();
            // 
            // hWindow_Fit1
            // 
            this.hWindowControlEx.BackColor = System.Drawing.Color.Transparent;
            this.hWindowControlEx.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.hWindowControlEx.DrawModel = false;
            this.hWindowControlEx.Image = null;
            this.hWindowControlEx.Location = new System.Drawing.Point(7, 20);
            this.hWindowControlEx.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
            this.hWindowControlEx.Name = "hWindow_Fit1";
            this.hWindowControlEx.Size = new System.Drawing.Size(643, 500);
            this.hWindowControlEx.TabIndex = 0;
            windowsFormsHost1.Child = this.hWindowControlEx;

            hWindowControlWPF1 = new HWindowControl();

        }

        void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (mynetworkstream != null)
            {
                myTcpClient.Close();
                mynetworkstream.Dispose();
                if (myReceiveMsgThread != null && myReceiveMsgThread.IsAlive)
                {
                    myReceiveMsgThread.Abort();
                    myReceiveMsgThread = null;
                }
                statusBar_GrayValue.Content = "服务器已断开！";
            }
        }
      
        private void btnOpenCoonection_Click(object sender, RoutedEventArgs e)
        {
           
                //创建并实例化IP终结点
                IPAddress addr = IPAddress.Parse(txt_ServerIP.Text);
                int port = Convert.ToInt32(txt_ServerPort.Text);
                IPEndPoint ipEndPoint = new IPEndPoint(addr, port);
                //实例化客户端
                myTcpClient = new TcpClient();
                //为了避免异常
                try
                {
                    //发起TCP链接
                    myTcpClient.Connect(ipEndPoint);
                    if (myTcpClient != null)
                        statusBar_GrayValue.Content = "服务器已连接！";
                    //绑定网络数据流
                    mynetworkstream = myTcpClient.GetStream();


                    //创建接收信息线程
                    myReceiveMsgThread = new Thread(ReceiveMsg);
                    //开启线程
                    myReceiveMsgThread.Start();


                    btnOpenCoonection.IsEnabled = false;
                    btnCloseConnection.IsEnabled = true;
                    btnSendData.IsEnabled = true;

                }
                catch (Exception ex)
                {
                    System.Windows.MessageBox.Show(ex.Message);
                    statusBar_GrayValue.Content = "服务器链接失败！";
                }
            
        }

        bool isRecevice;

        //创建一个方法，接收消息
        private void ReceiveMsg()
        {
            isRecevice = true;
            while (isRecevice)
            {
                try
                {
                    //获取数据
                    byte[] getData = new byte[1024];          //创建一个数组来存储接收到的数据
                    mynetworkstream.Read(getData, 0, getData.Length);//将接收到的数据放到数组中
                    //转换为字符串
                    string msg = Encoding.UTF8.GetString(getData);
                    ////将受到的信息添加到列表中

                    Dispatcher.Invoke(new Action(() => {

                        statusBar_GrayValue.Content = msg;
                    
                    }));
                    //lst_Receive.Invoke(showReceiveMsgCallBack, msg);
                    ////修改状态指示，因为是跨线程的，所以使用回调（委托）
                    //lab_state.Invoke(showLabStateCallBack, "数据接收中……"); ;
                    ////修改进度条的值
                    //pgb_Client.Invoke(showProgressBarCallBack);

                }
                catch (ThreadAbortException)
                {
                    //无操作，用来响应人为抛出的异常；
                }
                catch (Exception ex)
                {
                    //System.Windows.MessageBox.Show(ex.Message);//抛出异常的信息
                    if (mynetworkstream != null)//有可能网络数据流还没有建立
                        mynetworkstream.Dispose();
                    break;//当抛出异常后，需要break一下，才能终结；

                }
            }
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            if (mynetworkstream != null)
            {
                byte[] sendData;//定义发送数组
                //将数组进行字节编码，以便能够发送
                sendData = Encoding.UTF8.GetBytes(txt_SendMsg.Text);
                //发送，写入网络数据流中，括号中依次是：发送的数组，发送的开始位置，发送数据的长度
                mynetworkstream.Write(sendData, 0, sendData.Length);
            }


            
        }

        private void btnCloseConnection_Click(object sender, RoutedEventArgs e)
        {
            if (mynetworkstream != null)
            {

              
                myTcpClient.Close();
                mynetworkstream.Dispose();

                if (myReceiveMsgThread != null && myReceiveMsgThread.IsAlive)
                {
                    myReceiveMsgThread.Abort();
                    myReceiveMsgThread = null;
                }
               
                statusBar_GrayValue.Content= "服务器已断开！";
            }


            btnOpenCoonection.IsEnabled = true;
            btnCloseConnection.IsEnabled = false;
            btnSendData.IsEnabled = false;

        }

       

        private void MenuItem_OpenImage_Click(object sender, RoutedEventArgs e)
        {

            OpenFileDialog opnDlg = new OpenFileDialog();


            opnDlg.Filter = "所有图像文件 | *.bmp; *.pcx; *.png; *.jpg; *.gif;" +
                "*.tif;*.tiff; *.ico; *.dxf; *.cgm; *.cdr; *.wmf; *.eps; *.emf";


            opnDlg.Title = "打开图像文件";
            opnDlg.ShowHelp = false;
            opnDlg.Multiselect = false;
            if (opnDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {

                if (ho_ModelImage != null && ho_ModelImage.IsInitialized())
                {
                    ho_ModelImage.Dispose();
                    ho_ModelImage = null;
                }

                hWindowControlEx.ClearWindow();
                if (hWindowControlEx.Image != null && hWindowControlEx.Image.IsInitialized())
                {
                    hWindowControlEx.Image.Dispose();
                    hWindowControlEx.Image = null;
                }


                //读取图像
                ho_ModelImage = new HImage(opnDlg.FileName);

                

                //显示图像
                hWindowControlEx.DispImage(ho_ModelImage);

                if (mynetworkstream != null)
                {
                    byte[] sendData;//定义发送数组
                    //将数组进行字节编码，以便能够发送
                    sendData = Encoding.UTF8.GetBytes(opnDlg.FileName);
                    //发送，写入网络数据流中，括号中依次是：发送的数组，发送的开始位置，发送数据的长度
                    mynetworkstream.Write(sendData, 0, sendData.Length);
                }
            }

         
        }

        private void MenuItem_Close_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

         
    }
}
